package com.fivec.javaproject.generatebitaddress.code.generatekeys;

import com.fivec.javaproject.address.Address;

import java.security.*;
import java.security.interfaces.ECPrivateKey;
import java.security.interfaces.ECPublicKey;
import java.security.spec.ECGenParameterSpec;
import java.security.spec.ECPoint;

import static com.fivec.javaproject.generatebitaddress.code.tools.StaticMethod.adjustto64;

/**
 * @author wangyizhu
 * @version "1.8.0_131"
 * @email 2641956765@qq.com
 * @desc:该类用于生成ECDSA密钥和公钥，并返回
 * @Time 2021/12/06 19:19
 */
public class GenerateKey {
    KeyPairGenerator  keyGen;
    {
        try {
            //为Elliptic Curve算法创建KeyPairGenerator。
            keyGen = KeyPairGenerator.getInstance("EC");
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
    }
    //使用指定椭圆曲线是secp256k1。
    ECGenParameterSpec ecSpec = new ECGenParameterSpec("secp256k1");
    KeyPair kp = keyGen.generateKeyPair();
    public String getPriKey() {
        /**
         * 该方法用于生成密钥，并返回
         */
        PrivateKey pvt = kp.getPrivate();
        ECPrivateKey epvt = (ECPrivateKey) pvt;
        String sepvt = adjustto64(epvt.getS().toString(16)).toUpperCase();
        return sepvt;
    }
    public byte[] getPubKey() {
        /**
         * 该方法用于生成公钥，并返回
         */
        PublicKey pub = kp.getPublic();
        ECPublicKey epub = (ECPublicKey) pub;
        ECPoint pt = epub.getW();
        String sx = adjustto64(pt.getAffineX().toString(16)).toUpperCase();
        String sy = adjustto64(pt.getAffineY().toString(16)).toUpperCase();
        String bcPub = "04" + sx + sy;
        //S*ystem.out.println("公钥: " + bcPub);
        byte[] bcPubs = bcPub.getBytes();
        return bcPubs;
    }

    //该main用于测试
    public static void main(String[] args) {
        Address address=new Address();
        KeyPair keyPair = address.generateKeys();
        address.newAddress(keyPair);
    }
}
